package com.centling.smartSealForPhone.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.AppCompatSpinner;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.TextView;

import com.centling.smartSealForPhone.BuildConfig;
import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.constants.UrlConstants;
import com.centling.smartSealForPhone.constants.UserType;
import com.centling.smartSealForPhone.utils.DisplayUtil;
import com.fionera.base.util.MD5Util;
import com.centling.smartSealForPhone.utils.OkHttpUtil;
import com.centling.smartSealForPhone.utils.PhoneNumCheck;
import com.centling.smartSealForPhone.utils.ShowToast;
import com.centling.smartSealForPhone.view.RoundImgView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class AddUserActivity extends TitleBarActivity implements View.OnClickListener {
    private String filePath = Environment.getExternalStorageDirectory().getPath() + "/temp.jpg";
    private File tempFile = new File(filePath);
    private Uri imageUri;
    private EditText username;
    private EditText realname;
    private EditText password;
    private EditText phone;
    private EditText department;
    private AppCompatSpinner usertype;
    private RoundImgView avatar;
    private TextView cancel;
    private TextView save;
    private AlertDialog dialog;
    private Bitmap bitmap;

    private int userType = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_user);
        setTitleBarText("添加用户 ");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".FileProvider", tempFile);
        } else {
            imageUri = Uri.fromFile(tempFile);
        }

        initView();
    }

    public void initView() {
        username = (EditText) findViewById(R.id.et_add_user_username);
        realname = (EditText) findViewById(R.id.et_add_user_realname);
        password = (EditText) findViewById(R.id.et_add_user_pwd);
        phone = (EditText) findViewById(R.id.et_add_user_phone);
        usertype = (AppCompatSpinner) findViewById(R.id.sp_add_user_type);
        avatar = (RoundImgView) findViewById(R.id.riv_add_user_avatar);
        cancel = (TextView) findViewById(R.id.tv_add_user_cancel);
        save = (TextView) findViewById(R.id.tv_add_user_save);
        department = (EditText) findViewById(R.id.et_add_user_department);

        String[] items = new String[]{"设备管理员", "设备操作员", "普通用章人"};
        ArrayAdapter adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, items) {

            @NonNull
            @Override
            public View getView(int position, View convertView, @NonNull ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                ((TextView) view).setTextSize(17f);
                return view;
            }

            @Override
            public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                view.setPadding(DisplayUtil.dp2px(16f), DisplayUtil.dp2px(16f),
                        DisplayUtil.dp2px(16f), DisplayUtil.dp2px(16f));
                ((TextView) view).setTextSize(14f);
                return view;
            }
        };
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        usertype.setAdapter(adapter);
        usertype.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                userType = i;
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        avatar.setOnClickListener(this);
        cancel.setOnClickListener(this);
        save.setOnClickListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        try {
            if (resultCode != RESULT_CANCELED) {
                switch (requestCode) {
                    case 0:
                        startPhotoZoom(intent.getData());
                        break;
                    case Activity.DEFAULT_KEYS_DIALER:
                        startPhotoZoom(null);
                        break;
                    case 2:
                        bitmap = BitmapFactory.decodeFile(filePath);
                        avatar.setImageBitmap(bitmap);
                        break;
                    default:
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 裁剪图片方法实现
     */
    public void startPhotoZoom(Uri uri) {
        if (uri == null) {
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inSampleSize = 2;
            Bitmap originBitmap = BitmapFactory.decodeFile(filePath, opts);
            uri = Uri.parse(MediaStore.Images.Media
                    .insertImage(mContext.getContentResolver(), originBitmap, null, null));
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 400);
        intent.putExtra("outputY", 400);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(filePath)));
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("return-data", false);
        startActivityForResult(intent, 2);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.riv_add_user_avatar:
                if (dialog == null) {
                    dialog = new AlertDialog.Builder(AddUserActivity.this).setItems(new String[]{"相机", "相册"}, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (which == 0) {
                                Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
                                i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                                startActivityForResult(i, Activity.DEFAULT_KEYS_DIALER);
                            } else {
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_PICK);
                                intent.setType("image/*");
                                startActivityForResult(intent, 0);
                            }
                        }
                    }).create();
                }
                if (!dialog.isShowing()) {
                    dialog.show();
                }
                break;
            case R.id.tv_add_user_cancel:
                finish();
                break;
            case R.id.tv_add_user_save:
                String userName = username.getText().toString();
                final String realName = realname.getText().toString();
                String phoneNum = phone.getText().toString();
                String passWord = password.getText().toString();
                String department = this.department.getText().toString();

                if (TextUtils.isEmpty(userName)) {
                    ShowToast.shortTime("用户名不能为空");
                    return;
                }
//                if (userName.length() < 1) {
//                    ShowToast.shortTime("请输入1~20位用户名");
//                    return;
//                }
                if (TextUtils.isEmpty(realName)) {
                    ShowToast.shortTime("真实姓名不能为空");
                    return;
                }
                if (!TextUtils.isEmpty(phoneNum)&&!PhoneNumCheck.isMobileNo(phoneNum)) {
                    ShowToast.shortTime("请输入正确的手机号");
                    return;
                }
                if (TextUtils.isEmpty(passWord)) {
                    ShowToast.shortTime("密码不能为空");
                    return;
                }
                if (passWord.length() < 6) {
                    ShowToast.shortTime("请输入6~20位密码");
                    return;
                }
                if (TextUtils.isEmpty(department)) {
                    ShowToast.shortTime("请输入部门");
                    return;
                }

                String bitmapData;
                if (bitmap == null) {
                    bitmapData = "";
                } else {
                    ByteArrayOutputStream myStream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, myStream);
                    byte[] myCopyByte = myStream.toByteArray();
                    int myLength = myCopyByte.length;
                    bitmapData = Base64.encodeToString(myCopyByte, 0, myLength, Base64.DEFAULT);
                }
                Map<String, String> param = new HashMap<>();
                String type = "";
                switch (userType) {
                    case 0:
                        type = UserType.EQUIP_ADMIN;
                        break;
                    case 1:
                        type = UserType.EQUIP_OPERATOR;
                        break;
                    case 2:
                        type = UserType.EQUIP_COMMON_USER;
                        break;
                    default:
                        break;
                }
                param.put("userName", userName);
                param.put("phone", phoneNum);
                param.put("realName", realName);
                param.put("avatar", bitmapData);
                param.put("userType", type);
                param.put("password", MD5Util.md5(passWord));
                param.put("department", department);
                mProcessDialog.setTitle("正在添加用户").showNormal();
                postJsonEnqueue(UrlConstants.ADD_USER, param, new OkHttpUtil.NetCallBack() {
                    @Override
                    public void onSucceed(String json) {
                        mProcessDialog.dismiss();
                        ShowToast.shortTime("添加用户成功");
                        finish();
                    }

                    @Override
                    public void onFailed(String reason) {
                        mProcessDialog.dismiss();
                        ShowToast.shortTime(reason);
                    }
                });
            default:
                break;
        }
    }

}


